package com.bbs.pojo.dto;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.bbs.pojo.dto.message.*;
import com.bbs.pojo.Message;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Data
@NoArgsConstructor
public class MessageDto implements Serializable {
    private String messageId;
    private String receiverId;
    private String senderId;
    private LocalDateTime sendTime;
    private Integer type;
    private MessageContent content;
    private Boolean acknowledged;

    private static Map<Integer, Class<? extends MessageContent>> messageContentTypeMap = new HashMap<>();
    static{
        messageContentTypeMap.put(FriendApplicationMessageContent.MESSAGE_TYPE, FriendApplicationMessageContent.class);
        messageContentTypeMap.put(SystemMessageContent.MESSAGE_TYPE, SystemMessageContent.class);
        messageContentTypeMap.put(UserMessageContent.MESSAGE_TYPE, UserMessageContent.class);
        messageContentTypeMap.put(ReplyMessageContent.MESSAGE_TYPE, ReplyMessageContent.class);
    }

    public MessageDto(Message message){
        this.messageId = message.getMessageId();
        this.receiverId = message.getReceiverId();
        this.senderId = message.getSenderId();
        this.sendTime = message.getSentTime();
        this.type = message.getType();
        this.acknowledged = message.getAcknowledged();

        Class<? extends  MessageContent> clazz = messageContentTypeMap.get(this.type);
        if(clazz != null){
            this.content = JSON.parseObject(message.getContent(), clazz);
        }
    }

    /**
     * @param messageMap FastJson反序列化得到的LinkedHashMap
     */
    public MessageDto(LinkedHashMap<String, Object> messageMap){
        String contentJson = JSON.toJSONString(messageMap.get("content"));
        messageMap.remove("content");
        String messageJson = JSON.toJSONString(messageMap);
        Message message = JSON.parseObject(messageJson, Message.class);

        this.messageId = message.getMessageId();
        this.receiverId = message.getReceiverId();
        this.senderId = message.getSenderId();
        this.sendTime = message.getSentTime();
        this.type = message.getType();
        this.acknowledged = message.getAcknowledged();

        Class<? extends  MessageContent> clazz = messageContentTypeMap.get(this.type);
        if(clazz != null){
            this.content = JSON.parseObject(contentJson, clazz);
        }
    }
}
